﻿using System;
using TestingConcurrencyBenchmark.Helpers;

namespace TestingConcurrencyBenchmark.Problems.ReadersWriters
{
    internal class ReaderWriterSolution : IReaderWriter
    {
        private readonly LightSwitch _readLightSwitch;
        private readonly BenchmarkSemaphore _roomEmpty;

        public ReaderWriterSolution()
        {
            _readLightSwitch = new LightSwitch();
            _roomEmpty = new BenchmarkSemaphore(1);
        }

        #region IReaderWriter Members

        public void Write(Action action)
        {
            _roomEmpty.WaitOne();
            action();
            _roomEmpty.Release();
        }

        public void Read(Action action)
        {
            _readLightSwitch.Lock(_roomEmpty);
            action();
            _readLightSwitch.Unlock(_roomEmpty);
        }

        #endregion
    }
}